package com.jams.goodox.activity.mine.interaction;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.hangzhou.jin.customview.LoadView;
import com.jams.goodox.BaseFragment;
import com.jams.goodox.R;
import com.jams.goodox.activity.serve.PersonalRentingDetailActivity;
import com.jams.goodox.adapter.PictureGroupAdapter;
import com.jams.goodox.constant.AppConfig;
import com.jams.goodox.entity.Neighborhood;
import com.jams.goodox.entity.resp.CooperationResp;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.MineService;
import com.jams.goodox.utils.CollectionUtils;
import com.jams.goodox.utils.DelayUtils;
import com.jams.goodox.utils.StringUtils;
import com.jams.goodox.utils.UserUtils;
import com.jams.goodox.utils.ViewUtils;
import com.jams.goodox.widget.BlankClickGridView;
import com.jams.goodox.widget.RefreshRecyclerView;
import com.jams.goodox.widget.mannger.RefreshLinearLayoutManager;
import com.jams.library.commonAdapter.RecycleCommonAdapter;
import com.jams.library.commonAdapter.RecycleCommonViewHolder;
import com.jams.library.listener.OnRecycleItemClickListener;
import com.jams.library.widget.RecyclerDivider;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;

/**
 * Created by jams on 2016/10/12.
 * ***
 * Tel: ***
 * 我的互动-我的发布
 */
public class MinePublishFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {
    private static final String ARG_PARAM1 = "param1";
    View rootView;
    @Bind(R.id.rv_fragment_circle_mine_publish)
    RefreshRecyclerView refreshRecyclerView;
    @Bind(R.id.sdv_fragment_mine_publish)
    SwipeRefreshLayout swipeRefreshLayout;
    @Bind(R.id.loadView)
    LoadView loadView;
    private List<Neighborhood> dataList;
    private int curPage;
    private int clickItemPosition = -1;

    public static MinePublishFragment newInstance(String param1) {
        MinePublishFragment fragment = new MinePublishFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_mine_publish, container, false);
            // 初始化页面
            ButterKnife.bind(this, rootView);
            init();
        }
        return rootView;
    }

    private void init() {
        dataList = new ArrayList<>();
        curPage = 1;
        swipeRefreshLayout.setOnRefreshListener(this);
        refreshRecyclerView.setLayoutManager(new RefreshLinearLayoutManager(getActivity()));
        refreshRecyclerView.setHasFixedSize(true);
        refreshRecyclerView.setAdapter(new RecycleCommonAdapter<Neighborhood>(getActivity(), dataList, R.layout.item_enterprise_cooperation) {
            @Override
            public void convert(RecycleCommonViewHolder helper, Neighborhood item, int position) {
                setData(helper, item, position);
            }
        });
        refreshRecyclerView.addItemDecoration(new RecyclerDivider(
                mContext, LinearLayoutManager.VERTICAL, 1, ContextCompat.getColor(getContext(), R.color.shallow_divider)));
        onRefresh();
        refreshRecyclerView.notifyData();
        refreshRecyclerView.setLoadDataListener(new RefreshRecyclerView.LoadDataListener() {
            @Override
            public void onLoadMore() {
                // 开启线加载更多数据
                DelayUtils.doAfterDelay(300, new DelayUtils.DelayDoListener() {
                    @Override
                    public void doAction() {
                        getMyPublishList();
                    }
                });
            }
        });
    }

    //获取我发布的
    private void getMyPublishList() {
        enqueue(createCallService(MineService.class).myPublishInteraction(curPage, AppConfig.PagSize), new RetrofitCallbackListener<CooperationResp>() {
            @Override
            public void onSuccess(Call<CooperationResp> call, CooperationResp result) {
                try {
                    refreshRecyclerView.loadMoreComplete();
                    swipeRefreshLayout.setRefreshing(false);
                    if (result.data != null) {
                        if (curPage == 1) {
                            dataList.clear();
                        }
                        if (result.data.pageInfo == null) {
                            refreshRecyclerView.setCanLoadMore(false);
                        } else {
                            refreshRecyclerView.setCanLoadMore(result.data.pageInfo.isHasMore());
                        }
                        dataList.addAll(result.data.resultList);
                        curPage++;
                        refreshRecyclerView.notifyData();
                    }
                    if (!CollectionUtils.hasData(dataList)) {
                        loadView.loadCompleteNoData(R.mipmap.holder_no_common,R.string.no_content);
                    } else {
                        loadView.loadComplete();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(String msg) {
                try {
                    refreshRecyclerView.loadMoreComplete();
                    swipeRefreshLayout.setRefreshing(false);
                    if (!CollectionUtils.hasData(dataList)) {
                        loadView.loadCompleteNoData(R.mipmap.holder_no_common,R.string.no_content);
                    } else {
                        loadView.loadComplete();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }

    //设置每一个item数据
    private void setData(RecycleCommonViewHolder helper, final Neighborhood item, final int position) {
        try {
            helper.setSimpleDraweeView(R.id.sdv_innings_portrait_item, StringUtils.newString(item.getUserSimple().getPortraitUrl()))
                    .setText(R.id.tv_innings_name_item, item.getUserSimple().getNickName())
                    .setText(R.id.tv_innings_type_item, item.getLabel())
                    .setText(R.id.tv_innings_content, item.getTopicContent())
                    .setText(R.id.tv_innings_list_publish_time, item.getIntime())
                    .setText(R.id.tv_good_item, item.getTopicPraise() + "")
                    .setText(R.id.tv_comment_item, item.getTopicMsgcnt() + "");
            UserUtils.setSexImage(item.getUserSimple(),(ImageView) helper.getView(R.id.iv_sex));
            ViewUtils.setLabelWidth(mContext, (TextView) helper.getView(R.id.tv_innings_type_item));
            setImageList((BlankClickGridView) helper.getView(R.id.gv_innings_item), item, position);
            helper.setOnItemClickListener(new OnRecycleItemClickListener() {
                @Override
                public void itemClick() {
                    gotoDetailPage(item, position);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //设置图片
    private void setImageList(BlankClickGridView gridView, final Neighborhood item, final int mPosition) {
        gridView.setVisibility(View.VISIBLE);
        PictureGroupAdapter gridAdapter = new PictureGroupAdapter(getContext(), item.getAnnexs(), 80, 3);
        gridView.setAdapter(gridAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                gotoDetailPage(item, mPosition);
            }
        });
        gridView.setOnTouchBlankPositionListener(new BlankClickGridView.OnTouchBlankPositionListener() {
            @Override
            public void onTouchBlank(MotionEvent event) {
                gotoDetailPage(item, mPosition);
            }
        });
    }

    //跳转到详情页
    private void gotoDetailPage(Neighborhood item, int position) {//  2017/7/21 9:57 chenjian 跳转页面需要替换,目前只有官方租房
        clickItemPosition = position;
        
        Intent intent = new Intent(getActivity(), PersonalRentingDetailActivity.class);
        intent.putExtra(PersonalRentingDetailActivity.ID, StringUtils.newString(item.getId()));
        startActivityForResult(intent, 1991);
    }

    @Override
    public void onRefresh() {
        DelayUtils.doAfterDelay(100, new DelayUtils.DelayDoListener() {
            @Override
            public void doAction() {
                if (swipeRefreshLayout == null) {
                    return;
                }
                swipeRefreshLayout.setRefreshing(true);
                curPage = 1;
                getMyPublishList();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1991 && resultCode == 1993) {
            dataList.remove(clickItemPosition);
            refreshRecyclerView.notifyData();
        }
    }
}
